﻿#region << 文件说明 >>
/*----------------------------------------------------------------
 * 命名空间：Vampirewal.Core.WPF.Theme.CustomControl.NotifyIcon
 * 唯一标识：47c961e7-d66e-463e-8f8d-ab39e65f45fe
 * 文件名：VampirewalNotifyIcon
 * 
 * 创建者：杨程
 * 电子邮箱：235160615@qq.com
 * 创建时间：2025/4/29 16:36:03
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 文件说明 >>

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;


namespace Vampirewal.Core.WPF.Theme;

/// <summary>
/// 托盘图标
/// </summary>
internal sealed class VampirewalNotifyIcon
{
    private const int WM_LBUTTONDBLCLK = 0x0203;
    private const int WM_RBUTTONDOWN = 0x0204;
    private const int NIM_ADD = 0x00000000;
    private const int NIM_MODIFY = 0x00000001;
    private const int NIM_DELETE = 0x00000002;
    private const int NIF_MESSAGE = 0x00000001;
    private const int NIF_ICON = 0x00000002;
    private const int NIF_TIP = 0x00000004;

    private Window _window;
    private HwndSource _source;
    private NOTIFYICONDATA _iconData;
    private bool _isDisposed;

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    private struct NOTIFYICONDATA
    {
        public int cbSize;
        public IntPtr hWnd;
        public int uID;
        public int uFlags;
        public int uCallbackMessage;
        public IntPtr hIcon;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
        public string szTip;
    }

    [DllImport("shell32.dll", CharSet = CharSet.Auto)]
    private static extern bool Shell_NotifyIcon(int dwMessage, ref NOTIFYICONDATA lpData);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr DestroyIcon(IntPtr hIcon);

    public VampirewalNotifyIcon(Window window,List<MenuItem> menuItems,string iconName="VampirewalCore")
    {
        _window = window;
        IconName = iconName;

        Menu = new ContextMenu();

        SetContextMenu(menuItems);

        Menu.Placement = System.Windows.Controls.Primitives.PlacementMode.MousePoint;

        var i= System.Drawing.Icon.ExtractAssociatedIcon(Process.GetCurrentProcess().MainModule.FileName);

        InitializeIcon(i);

        _window.Closing += (s, e) => Dispose();
    }

    private string IconName { get; set; } 

    private void InitializeIcon(System.Drawing.Icon icon)
    {
        _iconData = new NOTIFYICONDATA
        {
            cbSize = Marshal.SizeOf(typeof(NOTIFYICONDATA)),
            hWnd = new WindowInteropHelper(_window).Handle,
            uID = 0,
            uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP,
            uCallbackMessage = WM_RBUTTONDOWN,
            hIcon = icon.Handle,
            szTip = IconName
        };

        if (!Shell_NotifyIcon(NIM_ADD, ref _iconData))
            throw new Win32Exception("Could not create tray icon");

        _source = HwndSource.FromHwnd(_iconData.hWnd);
        _source?.AddHook(WndProc);
    }

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == _iconData.uCallbackMessage)
            if ((int)lParam == WM_RBUTTONDOWN)
            {
                ShowContextMenu();
                handled = true;
            }
            else if ((int)lParam == WM_LBUTTONDBLCLK)
            {
                if(_window.WindowState== WindowState.Minimized)
                {
                    _window.WindowState = WindowState.Normal;
                }
                
                _window.Activate();
                handled = true;
            }
        return IntPtr.Zero;
    }

    private void SetContextMenu(List<MenuItem> menuItems)
    {
        //var menu = new System.Windows.Controls.ContextMenu();

        foreach (var item in menuItems)
        {
            Menu.Items.Add(item);
        }
    }

    private ContextMenu Menu { get; set; }

    private void ShowContextMenu()
    {
        //var menu = new System.Windows.Controls.ContextMenu();

        //// 创建菜单项
        //var exitItem = new System.Windows.Controls.MenuItem
        //{
        //    //Header = "Exit",
        //    //Command = new RelayCommand(() => Application.Current.Shutdown())
        //};

        //menu.Items.Add(exitItem);

        //设置菜单位置并打开
        //Menu.Placement = System.Windows.Controls.Primitives.PlacementMode.MousePoint;
        Menu.IsOpen = true;
    }

    public void Dispose()
    {
        if (_isDisposed) return;

        _iconData.uFlags = 0;
        Shell_NotifyIcon(NIM_DELETE, ref _iconData);
        DestroyIcon(_iconData.hIcon);

        _source?.RemoveHook(WndProc);
        _isDisposed = true;
    }

}